<?php

/*
 CI Library PayPal_IPN. A set of functions to work with paypal payments.
 Written by: Ciprian Dimofte - 02-08-2010
 */

class PayPal_IPN{
    public $CI;

    public function __construct(){
        $this->CI =& get_instance();
    }

    public function link($item){
        
    	//Get the correct ref_by
    	//If user is guest, than just take ref_by from the session otherwise just take it from the users table record corresponding to the user. 
    	if($this->CI->user->user_id > 0){
    		$ref_by = $this->CI->user->user_account['user_ref_by'];
    	}else{
    		$ref_by = $this->CI->session->userdata("ref_by");
    	}
    	
    	//Create the temporary order for this user.
    	$this->CI->db->query("
    	INSERT INTO tmp_orders
    	(
    	user_id,
    	ref_by,
    	plan_id,
    	paid_amount,
    	date,
    	ip,
    	vendor,
    	order_status
    	)
    	VALUES
    	(
    	'".$this->CI->user->user_id."',
    	'".$ref_by."',
    	'".$item['plan_id']."',
    	'".$item['amount']."',
    	'".time()."',
    	'".$this->CI->input->ip_address()."',
    	'PayPal',
    	'0'
    	)
    	");
    	$lastid = $this->CI->db->insert_id();

    	$out  = '<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" style="margin-bottom:0px; margin-top:0px;" name="pp">';
        //$out  = '<form action="https://www.paypal.com/cgi-bin/webscr" method="post" style="margin-bottom:0px; margin-top:0px;" name="pp">';
    	$out .= '<input type="hidden" name="cmd" value="_xclick" />';
    	$out .= '<input type="hidden" name="business" value="'.$this->CI->settings->get_param('paypal_email').'" />';
    	$out .= '<input type="hidden" name="item_name" value="'.$item['name'].' membership" />';
    	$out .= '<input type="hidden" name="item_number" value="'.$item['number'].'" />';
    	$out .= '<input type="hidden" name="notify_url" value="'.$this->CI->config->item("base_url").'util/verify_payment/paypal/'.$item['type'].'" />';

    	$out .= '<input type="hidden" name="return" value="'.$this->CI->config->item("base_url").'members/payment_complete" />';
    	$out .= '<input type="hidden" name="cancel_return" value="'.$this->CI->config->item("base_url").'members/cancelled_payment" />';
        $out .= '<input type="hidden" name="currency_code" value="USD" />';
        $out .= '<input type="hidden" name="custom" value="' . $lastid . '" />';
        $out .= '<input type="hidden" name="amount" value="'.$item['amount'].'" />';
        $out .= '<input type="submit" value="Pay with PayPal">';
        $out .= '</form>';

        return $out;
    }

    public function verify($transaction){

        $order_id = $this->CI->input->post('custom');

        $sel_order = $this->CI->db->query("
        SELECT * FROM tmp_orders
        WHERE
            ID = ?
        ", array($order_id));
        $res_order = $sel_order->row();

        // read the post from PayPal system and add 'cmd'
        $req = 'cmd=_notify-validate';
        foreach($_POST as $key => $value){
            $value = urlencode(stripslashes($value));
            $req .= "&$key=$value";
        }

        // post back to PayPal system to validate
        $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
        $fp = fsockopen ('www.sandbox.paypal.com', 80, $errno, $errstr, 30);
        //$fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30);

        // assign posted variables to local variables
        $item_name = $this->CI->input->post('item_name');
        $item_number = $this->CI->input->post('item_number');
        $payment_status = $this->CI->input->post('payment_status');
        $payment_amount = $this->CI->input->post('mc_gross');
        $payment_currency = $this->CI->input->post('mc_currency');
        $txn_id = $this->CI->input->post('txn_id');
        $receiver_email = $this->CI->input->post('receiver_email');
        $payer_email = $this->CI->input->post('payer_email');


        if (!$fp) {
            return "HTTP ERROR";
        }else{
            fputs ($fp, $header . $req);
            $res = fread($fp, 9094);
            if (strpos ($res, "VERIFIED") !== FALSE) {
                // check that txn_id has not been previously processed
                $selEx = $this->CI->db->query("SELECT txn_id FROM transactions WHERE txn_id = ?", array($txn_id));
                $resEx = $selEx->row();


                $acct_info = $this->CI->utility->get_account_type_by_plan_id($res_order->plan_id);

                if($item_number == $acct_info->ID && !$resEx->txn_id && $payment_amount == $res_order->paid_amount && $payment_currency == "USD" && $payment_status == "Completed" && $receiver_email == $this->CI->settings->get_param('paypal_email')){
                    //Record the transaction here
                    $this->CI->db->query("INSERT INTO transactions
                                              (
                                              user_id,
                                              transaction_type,
                                              transaction_amount,
                                              transaction_description,
                                              transaction_ip,
                                              transaction_date,
                                              txn_id
                                              )
                                          VALUES
                                              (
                                              ".$this->CI->db->escape($res_order->user_id).",
                                              ".$this->CI->db->escape($transaction['type']).",
                                              ".$this->CI->db->escape($payment_amount).",
                                              ".$this->CI->db->escape($item_name . " purchase").",
                                              ".$this->CI->db->escape($res_order->ip).",
                                              '".time()."',
                                              ".$this->CI->db->escape($txn_id)."
                                              )
                                         ");


                    $out = array(
                        "status"=>TRUE,
                        "ip"=>$res_order->ip,
                        "amount_paid"=>$payment_amount,
                        "plan_id"=>$res_order->plan_id,
                        "ref_by"=>$res_order->ref_by,
                        "uid"=>$res_order->user_id
                        );
                    $this->CI->db->query("
                    UPDATE tmp_orders SET order_status = '1'
                    WHERE
                        ID = '".$order_id."'
                    ");
                    return $out;
                }else{
                    return "Invalid";
                }
            }else{
                return "Invalid";
            }
        }
    }
}
?>